package com.huaxin.device.service;

import com.huaxin.device.dto.enums.AlarmLevel;
import com.huaxin.device.models.AlarmThresholdRule;
import com.huaxin.device.models.DeviceInstance;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * 报警消息参数自动提取器
 */
@Component
public class AlarmMessageParameterExtractor {
    private static final DateTimeFormatter DTF = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 从规则、设备、实时值等提取可用于消息模板的参数
     */
    public Map<String, Object> extractParameters(
            AlarmThresholdRule rule,
            DeviceInstance device,
            String currentValue,
            LocalDateTime triggerTime) {

        Map<String, Object> params = new HashMap<>();

        // 1. 设备信息
        if (device != null) {
            params.put("deviceName", device.getDeviceName());
            params.put("deviceId", device.getId());
            params.put("deviceModel", device.getModelCode());
            params.put("zoneName", device.getZoneName());
            params.put("location", device.getInstallLocation());
            params.put("deviceType", device.getDeviceType() != null ? device.getDeviceType().getDisplayName() : "未知类型");
        }

        // 2. 报警规则信息
        params.put("alarmType", rule.getAlarmType() != null ? rule.getAlarmType().getDisplayName() : "未知类型");
        params.put("thresholdValue", rule.getThresholdValue());
        params.put("unit", rule.getUnit() != null ? rule.getUnit().getDisplayName() : "");
        params.put("comparisonOp", rule.getComparisonOp() != null ? rule.getComparisonOp().getDisplayName() : "");
        params.put("durationSec", rule.getDurationSec());
        params.put("cooldownSec", rule.getCooldownSec());

        // 3. 触发时的实时值
        params.put("currentValue", currentValue != null ? currentValue : "未知");

        // 4. 报警等级（优先取规则，否则可从模板获取）
        AlarmLevel alarmLevel = rule.getAlarmLevel();
        params.put("alarmLevel", alarmLevel != null ? alarmLevel.getDisplayName() : "未知");

        // 5. 时间
        params.put("createdAt", triggerTime.format(DTF));
        params.put("triggerTime", triggerTime.format(DTF)); // 别名

        // 可扩展：添加组织、项目、负责人等

        return params;
    }
}
